//
//  Extension.swift
//  TestProject
//
//  Created by franze on 2017/9/13.
//  Copyright © 2017年 franze. All rights reserved.
//

import Foundation
import UIKit
import Photos

let WIDTH = UIScreen.main.bounds.width
let HEIGHT = UIScreen.main.bounds.height

extension Array{
    func size()->Int{
        return count > 0 ? count * MemoryLayout.size(ofValue: first) : 0
    }
}

extension UIImage{
    func scaleImageToSize(_ size:CGSize) -> UIImage{
        UIGraphicsBeginImageContextWithOptions(size,false,UIScreen.main.scale)
        self.draw(in: CGRect(x: 0,y: 0, width: size.width, height: size.height))
        let reSizeImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return reSizeImage
    }
    
    func clip(radius:CGFloat)->UIImage{
        UIGraphicsBeginImageContextWithOptions(CGSize(width:radius*2,height:radius*2), false, UIScreen.main.scale)
        let ctx = UIGraphicsGetCurrentContext()
        ctx?.addArc(center: CGPoint(x:radius,y:radius), radius: radius, startAngle: 0, endAngle: .pi/180 * 360, clockwise: true)
        ctx?.clip()
        self.draw(in: CGRect(origin: .zero, size: CGSize(width: radius*2, height: radius*2)))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    func flip()->UIImage{
        UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
        let ctx = UIGraphicsGetCurrentContext()
        ctx?.scaleBy(x: -1, y: 1)
        ctx?.translateBy(x: -self.size.width, y: 0)
        self.draw(in: CGRect(origin: .zero, size: self.size))
        let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}

extension String{
    func latinToGBTEncoding()->String{
        let GBTEnc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue))
        let data = self.data(using: .isoLatin1)
        return String(data: data!, encoding: String.Encoding(rawValue: GBTEnc))!
    }
}

extension UIView{
    func getParentController()->UIViewController?{
        var responder = self.next
        while (responder != nil) {
            if (responder?.isKind(of: UIViewController.self))!{
                return responder as? UIViewController
            }else{
                responder = responder?.next
            }
        }
        return nil
    }
}


